package org.fuxia.im.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.CommonDialog;
import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.socket.impl.ECNioClient;
import org.fuxia.im.entities.User;
import org.fuxia.im.utils.ImagePathUtils;
import org.tony.common.ui.CommonFrame;

import com.alibaba.fastjson.JSONArray;

public class FindFriend extends CommonFrame {

	private static final int OP_SIZE = 30 ;
	/**

	 */
	private static final long serialVersionUID = 1L;
	private final JPanel contentPane;
	private final JTextField friendNo;
	private final JTextField groupNo;
	private JTable friendsTable;
	private final JTabbedPane tabbedPane ;
	private final JPanel friendPanel;
	private JTable groupTabel ;
	private MyTableCellRenderer render;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FindFriend frame = new FindFriend();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public FindFriend() {
		super();
		render =  new MyTableCellRenderer() ;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setTitle("查找联系人");
		setResizable(false);
		setBounds(100, 100, 558, 407);
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContent(contentPane);

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBackground(Color.WHITE);
		tabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel.add(tabbedPane, BorderLayout.CENTER);

		friendPanel = new JPanel();
		friendPanel.setOpaque(false);
		tabbedPane.addTab("找人    ", new ImageIcon(Thread.currentThread().getContextClassLoader()
				.getResource("images/find1.jpg")), friendPanel, null);
		friendPanel.setLayout(null);

		JPanel panel_5 = new JPanel();
		panel_5.setBackground(Color.WHITE);
		panel_5.setBorder(UIManager.getBorder("FormattedTextField.border"));
		panel_5.setBounds(0, 0, 527, 76);
		friendPanel.add(panel_5);
		panel_5.setLayout(null);


		friendNo = new JTextField();
		friendNo.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		friendNo.setText("请输入联系人账号");
		friendNo.setColumns(10);
		friendNo.setBounds(41, 25, 357, 29);
		panel_5.add(friendNo);
		// 查找 好友
		JButton findbtn = new JButton("查找");
		findbtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				User my = ClientContext.getLoginUser();
				String friendText = friendNo.getText();
				
				ECPacket packet = new ECPacket();
				packet.setMessageType("QUERY_USER");
				packet.addParam("self", my.getUserCode());
				packet.addParam("condition", friendText);
				packet.setFrom(ClientContext.getLoginUser().getUserCode()) ;
				
				JDialog dialog = CommonDialog.createModelWaitDialog(getFindFriend());
				ClientContext.putValue(ClientConst.CURRENT_REQUESTOR, getFindFriend());
				ClientContext.putValue(ClientConst.CURRENT_WAITING_DIALOG, dialog);
				ECNioClient client = ClientContext.getContext().getClient();
				try
				{
					client.sendMessage(packet);
					dialog.setVisible(true);
				}
				catch (Exception e1)
				{
					e1.printStackTrace();
				}

			}
		});
		findbtn.setMargin(new Insets(1, 8, 1, 8));
		findbtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		findbtn.setBounds(408, 25, 71, 29);
		panel_5.add(findbtn);
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 90, 508, 230);
		scrollPane.setBorder(new TitledBorder(null, "用戶列表", TitledBorder.LEADING, TitledBorder.TOP,
				new Font("微软雅黑", Font.BOLD, 12), null));
		friendPanel.add(scrollPane);


		friendsTable = new JTable();
		friendsTable.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		scrollPane.setViewportView(friendsTable);
		friendsTable.setRowHeight(30);
		friendsTable.setModel(new MyTableModel(new Object[][] {},
				new String[]{"头像", "昵称", "账号", "性别", "年龄", ""}));
		friendsTable.setDefaultRenderer(friendsTable.getColumnClass(0),render);
		friendsTable.setDefaultRenderer(friendsTable.getColumnClass(5),render);
		friendsTable.setRowHeight(50) ;
		friendsTable.getColumnModel().getColumn(0).setPreferredWidth(24);
		friendsTable.getColumnModel().getColumn(5).setPreferredWidth(18);
		
		friendsTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (friendsTable.getSelectedColumn() == 5)
				{
					int rowIndex = friendsTable.getSelectedRow() ;
					
					String friendCode = friendsTable.getValueAt(rowIndex, 2).toString() ;
					String loginUserCode = ClientContext.getLoginUser().getUserCode() ;
					
					String path = friendsTable.getValueAt(rowIndex, 0).toString() ;
					String nickName = friendsTable.getValueAt(rowIndex, 1).toString() ;
					String sex = friendsTable.getValueAt(rowIndex, 3).toString() ;
					String age = friendsTable.getValueAt(rowIndex, 4).toString() ;
					
					//好友信息
					String[] user = {ImagePathUtils.getImagePath(path),nickName, friendCode, sex, age} ;

					
					User temp = ClientContext.findUserByCode(friendCode) ;
					int width = getFindFriend().getWidth() ;
					int height = getFindFriend().getHeight() ;
					int x = getFindFriend().getX() ;
					int y = getFindFriend().getY() ;
					if(temp == null) {
						AddFriend addFriend = new AddFriend(width, height, x, y, user, 0) ;
						ClientContext.getContext().put("addFriend", addFriend) ;
						addFriend.setVisible(true) ;
					}else {
						int flog = 0 ;
						String result = "[" +friendCode+"]已经是您的好友，不能重复添加。" ;
						AddFriendNext next = new AddFriendNext(width, height, x, y, result, flog, user) ;
						next.setVisible(true) ;
					}
				}
			}

		});
		
		JPanel groupSeachPanel = new JPanel();
		tabbedPane.addTab("找群     ", new ImageIcon(Thread.currentThread().getContextClassLoader()
				.getResource("images/find2.jpg")), groupSeachPanel, null);
		groupSeachPanel.setLayout(null);

		JPanel groupSearchToolBar = new JPanel();
		groupSearchToolBar.setBorder(UIManager.getBorder("FormattedTextField.border"));
		groupSearchToolBar.setLayout(null);
		groupSearchToolBar.setBounds(0, 0, 527, 76);
		groupSeachPanel.add(groupSearchToolBar);

		groupNo = new JTextField();
		groupNo.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		groupNo.setText("请输入群账号");
		groupNo.setColumns(10);
		groupNo.setBounds(41, 25, 357, 29);
		groupSearchToolBar.add(groupNo);

		// 查找群
		JButton findGroupBtn = new JButton("查找");
		findGroupBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String gn = groupNo.getText() ;
				if(gn.length() == 0) {
					CommonDialog.showErrorMessageDialog(getThis(), "群号必须输入");
					return ;
				}else {
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							User my = ClientContext.getLoginUser();
							ECPacket packet = new ECPacket();
							packet.setMessageType(ECMessageType.QUERY_GROUP.name());
							packet.addParam("userCode", my.getUserCode());
							packet.addParam("condition", groupNo.getText());
							packet.addParam("queryField", "id");
							packet.setFrom(ClientContext.getLoginUser().getUserCode()) ;
							JDialog dialog = CommonDialog.createModelWaitDialog(getFindFriend());
							ClientContext.putValue(ClientConst.CURRENT_REQUESTOR, getFindFriend());
							ClientContext.putValue(ClientConst.CURRENT_WAITING_DIALOG, dialog);
							ECNioClient client = ClientContext.getContext().getClient();
							try
							{
								client.sendMessage(packet);
								dialog.setVisible(true);
							}
							catch (Exception e1)
							{
								CommonDialog.showErrorMessageDialog(getThis(), "请检查网络连接状态");
							}
						}
					});
				}
			}

			
		});
		findGroupBtn.setMargin(new Insets(1, 14, 1, 14));
		findGroupBtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		findGroupBtn.setBounds(408, 25, 71, 29);
		groupSearchToolBar.add(findGroupBtn);
		
		JScrollPane groupTableScroll = new JScrollPane();
		groupTableScroll.setBorder(new TitledBorder(null, "群组列表", TitledBorder.LEADING, TitledBorder.TOP,
				new Font("微软雅黑", Font.BOLD, 12), null));
		groupTableScroll.setBounds(0,79,527,250);
		
		groupTabel = new JTable();
		groupTabel.setDefaultRenderer(JButton.class, new MyTableCellRenderer());
		groupTabel.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		groupTabel.setModel(new MyTableModel(
			new Object[][] {},
			new String[] {
				"群账户", "群名称","群创建人",""
			}
		));
		groupTabel.setRowHeight(30) ;
		groupTabel.setRowMargin(0);
		groupTabel.getColumnModel().getColumn(0).setMaxWidth(175);
		groupTabel.getColumnModel().getColumn(1).setMaxWidth(180);
		groupTabel.getColumnModel().getColumn(2).setMaxWidth(169);
		groupTabel.getColumnModel().getColumn(3).setWidth(OP_SIZE);
		groupTabel.getColumnModel().getColumn(3).setMaxWidth(OP_SIZE);
		groupTabel.getColumnModel().getColumn(3).setPreferredWidth(OP_SIZE);
		groupTabel.getColumnModel().getColumn(3).setMaxWidth(OP_SIZE);
		groupTabel.setDefaultRenderer(groupTabel.getColumnClass(3), render);
		groupTableScroll.setViewportView(groupTabel) ;
		groupTabel.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {
				int column = groupTabel.getSelectedColumn() ;
				if(column==3) {
					String message =JOptionPane.showInputDialog(getFindFriend(), "输入请求添加信息") ;
					int row = groupTabel.getSelectedRow() ;
					String groupId = groupTabel.getModel().getValueAt(row, 0).toString();
					String groupName = groupTabel.getModel().getValueAt(row, 1).toString();
					String ownerId = groupTabel.getModel().getValueAt(row, 2).toString();
					ECPacket packet = new ECPacket() ;
					packet.setMessageType(ECMessageType.ADD_GROUP.name()) ;
					packet.addParam("groupId", groupId);
					packet.addParam("groupName", groupName);
					packet.addParam("ownerId", ownerId);
					packet.addParam("userCode", ClientContext.getLoginUser().getUserCode()) ;
					packet.addParam("nickName", ClientContext.getLoginUser().getNickName()) ;
					packet.setFrom(ClientContext.getLoginUser().getUserCode()) ;
					if(message!=null && message.length()>0) {
						packet.addParam("extraInfo", message);
					}else {
						packet.addParam("extraInfo", "无");
					}
					try {
						ClientContext.getContext().getClient().sendMessage(packet);
					} catch (Exception e1) {
						CommonDialog.showErrorMessageDialog(getFindFriend(), "请检查网络连接");
					}
				}
			}
			
		});
		groupSeachPanel.add(groupTableScroll);

	}
	
	public void addData(List<JSONArray> groups){
		ImageIcon icon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/add1.jpg")) ;
		MyTableModel dtm = (MyTableModel)groupTabel.getModel();
		dtm.removeAll() ;
		for(JSONArray array:groups) {
			Object[] o = new Object[4] ;
			System.arraycopy(array.toArray(), 0, o, 0, array.size());
			o[3] = icon ;
			dtm.addRow(o);
		}
		groupTabel.repaint() ;
	}

	@Override
	public void dispose() {
		super.dispose();
		ClientContext.removeKey("findFrame") ;
	}
	private Component getThis() {
		return this;
	}

	public void addUsers(final List users)
	{
		DefaultTableModel dtm = (DefaultTableModel)friendsTable.getModel();
		ImageIcon icon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/add1.jpg")) ;
		ImageIcon defaultIcon = new ImageIcon(Thread.currentThread().getContextClassLoader()
				.getResource("images/tangling.jpg"));
		for (int i = 0; i < users.size(); i++)
		{
			JSONArray cur = (JSONArray) users.get(i);
			Object[] o = new Object[6];
			System.arraycopy(cur.toArray(), 0, o, 0, cur.size());
			URL url = Thread.currentThread().getContextClassLoader().getResource(o[0].toString());
			if (url == null)
			{
				o[0] = defaultIcon;
			}
			else
			{
				o[0] = new ImageIcon(url);
			}
			if (o[3] != null)
			{
				o[3] = o[3].toString().equals("0") ? "男" : "女";
			}
			else
			{
				o[3] = "未知";
			}
			if (o[4] == null)
			{
				o[4] = "0";
			}
			o[5] = icon;
			dtm.addRow(o) ;
		}
		friendsTable.repaint() ;
	}

	public JFrame getFindFriend() {
		return this;
	}
}
